#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/27 13:09
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : filter_email_config.py
# @Software: PyCharm
# @Desc    :

import django_filters

from common.utils.common import strip_filter
from semail.models import EmailConfig


class EmailConfigFilter(django_filters.FilterSet):
    """EmailConfig表过滤器：支持名称、SMTP服务器、默认状态等过滤"""
    # 配置名称：模糊查询（忽略大小写）
    name = django_filters.CharFilter(lookup_expr='icontains', method='filter_name')
    # SMTP服务器：模糊查询
    email_host = django_filters.CharFilter(lookup_expr='icontains', method='filter_email_host')
    # 是否默认配置：精确匹配（True/False）
    is_default = django_filters.BooleanFilter(field_name='is_default', lookup_expr='exact')
    # 启用状态：精确匹配（0=关闭，1=开启）
    is_active = django_filters.NumberFilter(field_name='is_active', lookup_expr='exact')

    def filter_name(self, queryset, name, value):
        """名称过滤：去空格后模糊匹配"""
        value = strip_filter(value)
        return queryset.filter(name__icontains=value) if value else queryset

    def filter_email_host(self, queryset, name, value):
        """SMTP服务器过滤：去空格后模糊匹配"""
        value = strip_filter(value)
        return queryset.filter(email_host__icontains=value) if value else queryset

    class Meta:
        model = EmailConfig
        fields = ['name', 'email_host', 'is_default', 'is_active', 'is_delete']

    @property
    def qs(self):
        """默认只返回「未删除+非压测」的有效配置"""
        parent_qs = super().qs
        return parent_qs.filter(is_delete=0, pt_flag=0)
